/*
 * Created by JFormDesigner on Sat Jun 27 11:23:37 CST 2020
 */

package mynote;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.*;
import java.sql.*;
import java.util.Scanner;

/**
 * @author Shawn Lou
 */
//登录窗口类
public class LoginFrame extends JFrame {
    public static final Color lblBtnColor = new Color(60, 114, 208);
    private static final String remFilePath = "src/mynote/data/info.txt";
    public LoginFrame() {
        initComponents();
        txtUsername.addFocusListener(new TextFocusListener("用户名", txtUsername));
        pwdPassword.addFocusListener(new PwdFocusListener("密码", pwdPassword));
        btnLogin.requestFocus();
        btnLogin.addActionListener(new LoginListener(this, txtUsername,
                pwdPassword));
        lblSignUp.addMouseListener(new SignUpListener(this, lblSignUp));
        getRem();
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        dialogPane = new JPanel();
        txtUsername = new JTextField();
        btnLogin = new JButton();
        pwdPassword = new JPasswordField();
        lblSignUp = new JLabel();
        chkRem = new JCheckBox();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        setTitle("My Note");
        setIconImage(new ImageIcon(getClass().getResource("/mynote/data/icon.png")).getImage());
        var contentPane = getContentPane();

        //======== dialogPane ========
        {
            dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));

            //---- txtUsername ----
            txtUsername.setToolTipText("\u7528\u6237\u540d");
            txtUsername.setBorder(new EmptyBorder(4, 4, 4, 4));

            //---- btnLogin ----
            btnLogin.setText("\u767b\u5f55");
            btnLogin.setBackground(SystemColor.activeCaption);
            btnLogin.setFocusPainted(false);

            //---- pwdPassword ----
            pwdPassword.setToolTipText("\u5bc6\u7801");
            pwdPassword.setBorder(new EmptyBorder(4, 4, 4, 4));
            pwdPassword.setMargin(new Insets(2, 6, 2, 6));

            //---- lblSignUp ----
            lblSignUp.setText("\u6ce8\u518c");

            //---- chkRem ----
            chkRem.setText("\u8bb0\u4f4f\u6211");

            GroupLayout dialogPaneLayout = new GroupLayout(dialogPane);
            dialogPane.setLayout(dialogPaneLayout);
            dialogPaneLayout.setHorizontalGroup(
                dialogPaneLayout.createParallelGroup()
                    .addGroup(dialogPaneLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(dialogPaneLayout.createParallelGroup()
                            .addComponent(btnLogin, GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                            .addComponent(pwdPassword, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                            .addComponent(txtUsername, GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                            .addGroup(dialogPaneLayout.createSequentialGroup()
                                .addComponent(chkRem, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 151, Short.MAX_VALUE)
                                .addComponent(lblSignUp)))
                        .addContainerGap())
            );
            dialogPaneLayout.setVerticalGroup(
                dialogPaneLayout.createParallelGroup()
                    .addGroup(dialogPaneLayout.createSequentialGroup()
                        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtUsername, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(pwdPassword, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnLogin)
                        .addGap(11, 11, 11)
                        .addGroup(dialogPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                            .addComponent(lblSignUp)
                            .addComponent(chkRem)))
            );
        }

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addComponent(dialogPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE))
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addComponent(dialogPane, GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                    .addContainerGap())
        );
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JPanel dialogPane;
    private JTextField txtUsername;
    private JButton btnLogin;
    private JPasswordField pwdPassword;
    private JLabel lblSignUp;
    private JCheckBox chkRem;
    // JFormDesigner - End of variables declaration  //GEN-END:variables

    //登录时匹配用户名和密码
    public static boolean login(String username, String password) {
        Connection con = null;
        Statement sta = null;
        ResultSet res = null;
        try {
            Class.forName(MyDB.driver);
            con = DriverManager.getConnection(MyDB.url, MyDB.userDB, MyDB.pwdDB);
            sta = con.createStatement();
            res = sta.executeQuery("select username, password from user");
            while (res.next()) {
                String name = res.getString(1);
                String pwd = res.getString(2);
                if (username.equals(name) && password.equals(pwd)) {
                    //存在匹配的用户
                    return true;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            MyDB.closeDB(con, sta, res);
        }
        return false;
    }

    //记住密码，输出至文件
    public void rememberMe() {
        if (!chkRem.isSelected()) {
            //未勾选记住密码，删除文件
            File file = new File(remFilePath);
            if (file.exists()) {
                    file.delete();
            }
            return;
        }
        //写入文件
        String username = txtUsername.getText() + " ";
        String pwd = String.valueOf(pwdPassword.getPassword());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(remFilePath);
            fos.write(username.getBytes());
            fos.write(pwd.getBytes());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                fos.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //从文件读入记住的信息
    public void getRem() {
        String username = "";
        String pwd = "";
        Scanner scan;
        FileInputStream fis;
        try {
            fis = new FileInputStream(remFilePath);
            scan = new Scanner(fis);
            username = scan.next();
            pwd = scan.next();
            fis.close();
        }
        catch (FileNotFoundException e) {
            return;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //自动填充用户名和密码
        txtUsername.setText(username);
        txtUsername.setForeground(Color.BLACK);
        pwdPassword.setText(pwd);
        pwdPassword.setForeground(Color.BLACK);
        pwdPassword.setEchoChar('\u2022');
        //并自动勾选记住我
        chkRem.setSelected(true);
    }
    public static void main(String[] args) {
        LoginFrame frame = new LoginFrame();
        frame.setVisible(true);
    }

}
